package tcp

import (
	"core/server/baseserver"
	"fmt"
	getty "github.com/apache/dubbo-getty"
	"github.com/dubbogo/gost/log/logger"
	"iotall/iotcore/entity"
	"net"
	"strconv"
	"time"
)

type TcpServer struct {
	Server   getty.Server
	CommPort *entity.CommPort
}

func (p *TcpServer) SetCommPort(m *entity.CommPort) {
	p.CommPort = m
}

func (p *TcpServer) Start() {

	options := []getty.ServerOption{getty.WithLocalAddress(":" + strconv.Itoa(int(p.CommPort.Port)))}
	p.Server = getty.NewTCPServer(options...)
	p.Server.RunEventLoop(p.NewSession)
	logger.Infof("TcpServer 代理 %v 启动 端口:%d", p.CommPort.Name, p.CommPort.Port)
	baseserver.AddServer(p)
}
func (p *TcpServer) Close() {
	p.Server.Close()
	logger.Infof("TcpServer 代理 %v 关闭 端口:%d", p.CommPort.Name, p.CommPort.Port)
}
func (p *TcpServer) NewSession(session getty.Session) error {
	var (
		ok      bool
		tcpConn *net.TCPConn
	)

	if tcpConn, ok = session.Conn().(*net.TCPConn); !ok {
		panic(fmt.Sprintf("%s, session.conn{%#v} is not tcp connection\n", session.Stat(), session.Conn()))
	}

	tcpConn.SetNoDelay(true)
	tcpConn.SetKeepAlive(true)
	tcpConn.SetKeepAlivePeriod(10 * time.Second)

	tcpConn.SetReadBuffer(int(p.CommPort.ReadBuffer))
	tcpConn.SetWriteBuffer(int(p.CommPort.WriteBuffer))

	//session.SetName(string(p.CommPort.Port))
	session.SetMaxMsgLen(1024)
	session.SetPkgHandler(&PkgHandler{Server: p})
	session.SetEventListener(&MsgHandler{Server: p})
	session.SetReadTimeout(30 * time.Second)
	session.SetWriteTimeout(5 * time.Second)
	session.SetCronPeriod(30000)
	session.SetWaitTime(20 * time.Second)

	return nil
}

func (p *TcpServer) Stop() {
	p.Server.Close()
	logger.Infof("TcpServer Stop:%d", p.CommPort.Port)
}
